package second.binarytree;



import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Solution03 {
    public List<Integer> preorderTraversal(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.removeLast();
            res.add(node.val);
            if (node.right != null) queue.add(node.right);
            if (node.left != null) queue.add(node.left);
        }
        return res;
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        TreeNode cur = root;
        while (cur != null || !queue.isEmpty()) {
            if (cur != null) {
                queue.add(cur);
                cur = cur.left;
            } else {
                TreeNode node = queue.removeLast();
                res.add(node.val);
                cur = node.right;
            }
        }
        return res;
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.removeLast();
            if (node.left != null) queue.add(node.left);
            if (node.right != null) queue.add(node.right);
        }
        Collections.reverse(res);
        return res;
    }

}
